
package cn.org.seventh.web.tag;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
import org.springframework.context.support.ResourceBundleMessageSource;

/**
 * @jsp.tag name="date"
 * @author <a href="mailto:ji.li@symbio-group.com">Andy</a>
 * @since Dec 3, 2007 10:54:38 AM
 */
public class DateTag extends BaseTag {

    private static final long serialVersionUID = -8304356815380858616L;

    private final transient Log log = LogFactory.getLog(DateTag.class);

    private static final String DEFAULT_PATTERN = "yyyy-MM-dd";

    private String pattern;

    private String patternKey;

    private Date date;

    /**
     * @jsp.attribute required = "true" rtexprvalue="true"
     */
    public void setDate(String date) {
        try {
            String str =
                (String) ExpressionEvaluatorManager.evaluate("date", date,
                    String.class, pageContext);
            SimpleDateFormat dateFormat =
                new SimpleDateFormat("yyy-MM-dd hh:mm:ss.S");
            this.date = dateFormat.parse(str);
        } catch (Exception e) {
            log.debug(e);
        }
    }

    /**
     * @jsp.attribute required = "false"
     */
    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    /**
     * @jsp.attribute required = "false"
     */
    public void setPatternKey(String patternKey) {
        this.patternKey = patternKey;
    }

    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();
        if (date == null) {
            return super.doEndTag();
        }
        if (patternKey != null) {
            HttpServletRequest request =
                (HttpServletRequest) pageContext.getRequest();
            ResourceBundleMessageSource messageSource = getMessageSource();
            pattern =
                messageSource.getMessage(patternKey, null, DEFAULT_PATTERN,
                    request.getLocale());
        }
        if (pattern == null) {
            pattern = DEFAULT_PATTERN;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            out.print(sdf.format(date));
        } catch (IOException e) {
            log.debug(e);
        }
        return super.doEndTag();
    }
}
